<?php
namespace App\Http\Controllers\Api\Customer;

use Carbon\Carbon;

use App\Models\SysRegion;

use Illuminate\Http\Request;

use App\Models\Deliver\Deliver;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

class CustomerDeliverController extends Controller
{


    /**
     * 列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function search( Request $request ) {

        $limit = $request->input('limit',10);
        $page = $request->input('page',1);
        $session_id = $request->input('session_id', session_id());
        if ( empty( $session_id ) ) {
            return response()->json(['code'=>100001,'message'=>'缺少参数：session_id']);
        }

        $pcustID = 0;

        $wx_applet_info = Redis::get('WX_APPLET_USER_' .$session_id);
        if ( $wx_applet_info ) {
            $wx_applet_info =  json_decode($wx_applet_info, true);
            if (isset($wx_applet_info['pcustID']) && ebsig_is_int($wx_applet_info['pcustID'])) {
                $pcustID = $wx_applet_info['pcustID'];
            }
        }

        if ( $pcustID <= 0 ) {
            return response()->json(['code'=>100002,'message'=>'请先登录']);
        }

        $field = ['deliverID', 'custName', 'provinceName', 'cityName', 'countyName', 'provinceid', 'cityid', 'countyid', 'address', 'mobile','is_default'];

        $deliver = Deliver::select( $field )->where('pcustID',$pcustID)->orderBy('is_default', 'DESC')->paginate($limit)->toArray();

        if ( !$deliver ) {
            return response()->json(['code' => 100003, 'message' => '暂无收货地址', 'data' => '']);
        }

        $return_data = [];

        foreach ( $deliver['data'] as &$item ) {
            $return_data[] = [
                'deliverID' => $item['deliverID'],
                'provinceName' => $item['provinceName'],
                'cityName' => $item['cityName'],
                'countyName' => $item['countyName'],
                'provinceid' => $item['provinceid'],
                'cityid' => $item['cityid'],
                'countyid' => $item['countyid'],
                'address' => $item['address'],
                'custName' => $item['custName'],
                'mobile' => $item['mobile'],
                'is_default' => $item['is_default']
            ];
        }

        $data = [
            'count' => $deliver['total'] ? $deliver['total'] : 0,
            'limit' => $limit,
            'page' => $page,
            'list' => $return_data
        ];

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $data]);
    }


    /**
     * 获取收货地址信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail( Request $request )
    {

        $deliver_id = $request->input('deliverID');
        $session_id = $request->input('session_id', session_id());

        if ( empty( $session_id ) ) {
            return response()->json(['code'=>100000,'message'=>'缺少参数：session_id']);
        }

        if ( empty( $deliver_id ) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数:deliverID']);
        }

        $deliver = Deliver::find( $deliver_id );

        if ( empty( $deliver ) ) {
            return response()->json(['code' => 100002, 'message' => '地址信息不存在']);
        }

        $return_data = [
            'cityid' => $deliver['cityid'],
            'mobile' => $deliver['mobile'],
            'address' => $deliver['address'],
            'countyid' => $deliver['countyid'],
            'deliverID' => $deliver['deliverID'],
            'cityName' => $deliver['cityName'],
            'provinceid' => $deliver['provinceid'],
            'countyName' => $deliver['countyName'],
            'provinceName' => $deliver['provinceName'],
            'is_default' => $deliver['is_default'],
            'custName' => $deliver['custName']
        ];

        return response()->json(['code' => 200, 'message' => 'ok','data'=>$return_data]);

    }


    /**
     * 设置默认收获地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function setDefault( Request $request )
    {
        $deliver_id = $request->input('deliverID');

        $session_id = $request->input('session_id');

        if ( empty( $deliver_id ) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数:deliverID']);
        }

        if ( empty( $session_id ) ) {
            return response()->json(['code'=>100002,'message'=>'缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, 6);
        if (!$pcustID) {
            return response()->json([ 'code' => 100002 , 'message' => '会员未登录' ]);
        }

        $deliver = Deliver::find( $deliver_id )->toArray();

        if ( empty( $deliver ) ) {
            return response()->json(['code' => 100003, 'message' => '地址信息不存在']);
        }

        $pcustID = $deliver['pcustID'];


        $result = Deliver::where(['pcustID' => $pcustID, 'is_default' => 1])->first();

        if( !empty($result) ) {
            Deliver::where(['pcustID' => $pcustID, 'is_default' => 1])->update(['is_default' => 0]);
        }

        Deliver::where(['deliverID' => $deliver_id ])->update(['is_default' => 1]);

        //清除收货地址缓存
        $redis_key = 'WDH_API_CUSTOMER_DELIVER_' . $session_id;

        Redis::del($redis_key);

        return response()->json(['code' => 200, 'message' => '设置默认成功' ]);

    }

    /**
     * 添加、修改
     */
    public function edit( Request $request )
    {

        $session_id = $request->input('session_id', session_id());
        $custName = $request->input('custName');
        $provinceid = $request->input('provinceid');
        $cityid = $request->input('cityid');
        $countyid = $request->input('countyid');
        $address = $request->input('address');
        $mobile = $request->input('mobile');
        $deliverID = $request->input('deliverID', 0);
        $postalCode = $request->input('postalCode', null);
        $is_default = $request->input('is_default', 0);
        $mallID = $request->input('mallID', null);
        $zt_id = $request->input('zt_id', 0);

        $pcustID = get_customer_id($session_id, 6);
        if (!$pcustID) {
            return response()->json([ 'code' => 100002 , 'message' => '会员未登录' ]);
        }

        if ( empty( $custName ) ) {
            return response()->json(['code' => 100001, 'message' => '收货人不能为空，请填写']);
        }

        if ( empty( $provinceid ) || empty( $cityid ) ) {
            return response()->json(['code' => 100001, 'message' => '请选择省市区']);
        }

        if ( empty( $address ) ) {
            return response()->json(['code' => 100001, 'message' => '收货地址不能为空，请填写']);
        }

        if ( empty( $mobile ) ) {
            return response()->json(['code' => 100001, 'message' => '手机号必填']);
        }

        $province = SysRegion::where(['id' => $provinceid, 'region_level' => 1])->first();

        if ( empty($province) ) {
            return response()->json(['code' => 100001, 'message' => '省份信息没有找到']);
        }

        $city = SysRegion::where(['id' => $cityid, 'region_level' => 2])->first();

        if ( empty($city) ) {
            return response()->json(['code' => 100001, 'message' => '市区信息没有找到']);
        }

        $county = SysRegion::where(['id' => $countyid, 'region_level' => 3])->first();

        if ( empty($county) ) {
            return response()->json(['code' => 100001, 'message' => '地区信息没有找到']);
        }

        if ( !$deliverID ) {
            $deliverID = generate_seqno('seqno_custdeliver');
            $data['uuid'] = makeUuid();
            $data['timeStamp'] = Carbon::now();
            $data['creator'] = $pcustID;
            $data['createTime'] = Carbon::now();
            $data['editor'] = $pcustID;
            $data['deliverID'] = $deliverID;
            $data['pcustID'] = $pcustID;
            $data['custName'] = $custName;
            $data['mobile'] = $mobile;
            $data['provinceName'] = $province->name;
            $data['cityName'] = $city->name;
            $data['countyName'] = $county->name;
            $data['provinceid'] = $provinceid;
            $data['cityid'] = $cityid;
            $data['countyid'] = $countyid;
            $data['address'] = $address;
            $data['postalCode'] = $postalCode;

            if ( $mallID ) {
                $data['mallID'] = $mallID;
                $data['mallName'] = $request->input('mallName', null);
                $data['mallCode'] = $request->input('mallCode', null);
            }

            if ( $zt_id ) {
                $data['zt_id'] = $zt_id;
                $data['zt_name'] = $request->input('zt_name', null);
                $data['zt_code'] = $request->input('zt_code', null);
            }

            if ( $is_default == 1 ) {

                Deliver::where(['is_default' => 1, 'pcustID' => $pcustID])->update(['is_default' => 0]);

                $data['is_default'] = 1;

            } else {
                $data['is_default'] = 0;
            }

            Deliver::insert($data);

        } else  {

            $data['editor'] = $pcustID;
            $data['pcustID'] = $pcustID;
            $data['custName'] = $custName;
            $data['mobile'] = $mobile;
            $data['provinceName'] = $province->name;
            $data['cityName'] = $city->name;
            $data['countyName'] = $county->name;
            $data['provinceid'] = $provinceid;
            $data['cityid'] = $cityid;
            $data['countyid'] = $countyid;
            $data['address'] = $address;
            $data['postalCode'] = $postalCode;

            if ( $mallID ) {
                $data['mallID'] = $mallID;
                $data['mallName'] = $request->input('mallName', null);
                $data['mallCode'] = $request->input('mallCode', null);
            }

            if ( $zt_id ) {
                $data['zt_id'] = $zt_id;
                $data['zt_name'] = $request->input('zt_name', null);
                $data['zt_code'] = $request->input('zt_code', null);
            }

            if ( $is_default == 1 ) {

                Deliver::where(['is_default' => 1, 'pcustID' => $pcustID])->update(['is_default' => 0]);

                $data['is_default'] = 1;

            } else {
                $data['is_default'] = 0;
            }

            Deliver::where(['deliverID' => $deliverID])->update($data);
        }

        return response()->json(['code' => 200, 'message' => '保存成功' ,'data' => ['deliverID' => $deliverID]]);

    }

    /**
     * 删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del( Request $request )
    {

        $deliver_id = $request->input('deliverID');

        $session_id = $request->input('session_id', session_id());

        if ( empty( $deliver_id ) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数:deliverID']);
        }

        if ( empty( $session_id ) ) {
            return response()->json(['code'=>100002,'message'=>'缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, 6);
        if (!$pcustID) {
            return response()->json([ 'code' => 100002 , 'message' => '会员未登录' ]);
        }

        $deliver = Deliver::find( $deliver_id )->toArray();

        if ( empty( $deliver ) ) {
            return response()->json(['code' => 100003, 'message' => '地址信息不存在']);
        }

        Deliver::where(['deliverID' => $deliver_id])->delete();

        //清除收货地址缓存
        $redis_key = 'WDH_API_CUSTOMER_DELIVER_' . $session_id;

        Redis::del($redis_key);

        return response()->json(['code' => 200, 'message' => '删除地址成功' ]);

    }



}